/*
 * Licensed under the MIT License
 * 
 * Copyright (c) 2011 Kay Kreuning
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 * 
 * http://code.google.com/p/hyves-as3-sdk/
 */
package nl.hyves.api.utils
{
	import com.adobe.serialization.json.JSONDecoder;

	import flash.utils.Dictionary;

	public class JSONMapper
	{
		private static const NAME_EXPRESSION:RegExp = new RegExp(/(?<=^\{")\w+/);
		private static var voMap:Dictionary;

		public static function registerMapping(associatedName:String, voClass:Class):void
		{
			voMap ||= new Dictionary();
			
			if (!voMap[associatedName])
			{
				voMap[associatedName] = voClass;
			}
		}

		public static function map(response:String):*
		{
			var name:String = NAME_EXPRESSION.exec(response);
			var decoded:Object = new JSONDecoder(response, true).getValue();

			if (!voMap[name])
			{
				return decoded;
			}

			return mapObject(decoded[name], name);
		}

		private static function mapObject(object:Object, objectName:String):*
		{
			if (!(object is Array))
			{
				object = [object];
			}

			var results:Array = new Array();

			for each (var item:Object in object)
			{
				var vo:Object = buildVOInstance(objectName);

				for (var property:String in item)
				{
					if (isPrimitive(item[property]))
					{
						if (item[property] == 'true' || item[property] == 'false')
						{
							vo[property] = (item[property] == 'true');
						}
						else
						{
							vo[property] = item[property];
						}
					}
					else
					{
						vo[property] = mapObject(item[property], property);
					}
				}

				results.push(vo);
			}

			return (results.length == 1) ? results[0] : results;
		}

		private static function buildVOInstance(name:String):*
		{
			if (voMap[name])
			{
				return new voMap[name]();
			}

			return new Object();
		}

		private static function isPrimitive(value:Object):Boolean
		{
			return (value is String) || (value is int);
		}
	}
}